package com.cloud.demo2020;

import com.alibaba.fastjson.JSONObject;
import com.cloud.demo2020.common.ResultBean;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

@Component
public class TokenFilter implements GlobalFilter {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Reference
    private UserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest req = exchange.getRequest();
        HttpCookie cookie = exchange.getRequest().getCookies().getFirst("cloud-token");
        String uri = req.getPath().value();

        if (cookie != null) {
            String token = cookie.getValue();
            String url = "http://user-service/user/info/" + token;
            ResultBean r = this.userService.info(token);
            if (r.isSuccess()) {
                return chain.filter(exchange);
            }

            return getVoidMono(exchange, r);
            //return
        } else {
            if (uri.indexOf("/user/info") == -1) {
                return chain.filter(exchange);
            } else {
                ResultBean error = new ResultBean(false, "同学,请先进行登录或注册");
                error.setCode(403);
                //ServerHttpResponse resp = exchange.getResponse();
                return getVoidMono(exchange, error);
            }
        }
    }

    private Mono<Void> getVoidMono(ServerWebExchange serverWebExchange, ResultBean body) {
        ServerHttpResponse resp = serverWebExchange.getResponse();
        resp.setStatusCode(HttpStatus.OK);
        byte[] bytes = JSONObject.toJSONString(body).getBytes(Charset.defaultCharset());
        DataBuffer buffer = resp.bufferFactory().wrap(bytes);
        resp.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        return resp.writeWith(Mono.just(buffer));
    }
}
